import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Divider, message, Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ BankLimit, loading }) => ({
  BankLimit,
  loading: loading.models.BankLimit,
}))

@Form.create()
class BankLimit extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };

  status(val) {
    let str = '';
    if (val === 1) {
      str = '启用';
    } else {
      str = val === 2 ? '停用' : '删除';
    }
    return (<span>{str}</span>);
  }

  columns = [
    {
      title: '限额编码',
      dataIndex: 'bankNo',
    },
    {
      title: '银行中文全称',
      dataIndex: 'bankName',
    },

    {
      title: '英文缩写',
      dataIndex: 'bankEngName',
    },
    {
      title: '创建人',
      dataIndex: 'createName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '限额描述',
      dataIndex: 'remark',
    },

    {
      title: '状态',
      dataIndex: 'status',
      render: val => (this.status(val)),
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {
            powerBtnFunc('100077', [
              <a key={'edit'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
              <Divider key={'divider'} type="vertical"/>])
          }
          {
            powerBtnFunc('100075', [
              <a key={'edit'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
              <Divider key={'divider'} type="vertical"/>,
            ])}
          {powerBtnFunc('100078', [
            <a key={'status'} onClick={() => this.onChange(record)}>{record.status === 1 ? '停用' : '启用'}</a>,
            <Divider key={'divider'} type="vertical"/>,
          ])}
          {powerBtnFunc('100079',
            <a key={'del'} onClick={() => this.handleDelClick(record)}>删除</a>)}
        </Fragment>
      ),
    },
  ];

  onChange(record) {

    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'BankLimit/status',
      payload: {
        bankNo: record.bankNo,
        status: record.status === 1 ? 2 : 1,
      },
      callback: (res) => {
        if (res.code === 200) {
          message.success('修改成功');
          dispatch({
            type: 'BankLimit/fetch',
            payload: pagination,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });
  }

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'BankLimit/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };

    dispatch({
      type: 'BankLimit/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'BankLimit/fetch',
      payload: {},
    });
  };
  handleDelClick = (row) => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: `确定`,
      content: `你确定删除该银行限额吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'BankLimit/remove',
          payload: {
            code: row.bankNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('删除成功');
              dispatch({
                type: 'BankLimit/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });

  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'BankLimit/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'BankLimit/getDesc',
          payload: { bankNo: record.bankNo },
        });
      }
    });

  };
  // 新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'BankLimit/add',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'BankLimit/fetch',
        });
      },
    });

    this.handleModalVisible();
  };
  // 修改请求
  handleUpdate = fields => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'BankLimit/update',
      payload: fields,
      callback: () => {
        dispatch({
          type: 'BankLimit/fetch',
          payload: pagination,

        });
        this.handleUpdateModalVisible(false, []);
      },
    });

  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="银行编码">
              {getFieldDecorator('bankNo')(<Input placeholder="请输入银行编码"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="银行全称">
              {getFieldDecorator('bankName')(<Input placeholder="请输入银行全称"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="英文缩写">
              {getFieldDecorator('bankEngName')(<Input placeholder="请输入英文缩写"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>

      </Form>
    );
  }


  render() {
    const { BankLimit: { data, Desc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="限额管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {powerBtnFunc('100076',
                <Button icon="plus" key={'create'} type="primary" onClick={() => this.handleModalVisible(true)}>
                  新建
                </Button>,
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowSelectHide={true}
              rowKey='bankNo'
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={Desc ? Desc : {}}
          lookDescView={lookDescView}/>

        <UpdateForm
          {...updateMethods}
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
        />
      </PageHeaderWrapper>
    );
  }
}

export default BankLimit;
